package mmc.gl.shader;

import static org.lwjgl.opengl.GL20.GL_COMPILE_STATUS;
import static org.lwjgl.opengl.GL20.glCompileShader;
import static org.lwjgl.opengl.GL20.glCreateShader;
import static org.lwjgl.opengl.GL20.glDeleteShader;
import static org.lwjgl.opengl.GL20.glGetShader;
import static org.lwjgl.opengl.GL20.glGetShaderInfoLog;
import static org.lwjgl.opengl.GL20.glShaderSource;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;

import org.lwjgl.opengl.GL11;

public class Shader {
	private final String name;
	private final int id;
	
	public Shader(String name){
		this.name = name;
		id = glCreateShader(ShaderType.guessTypeViaName(name).getGLConstant());
		
		create();
	}
	
	private void create(){
		try {
			InputStream in = ClassLoader.getSystemResourceAsStream(name);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] tmp = new byte[1024];
			int len;
			
			while((len=in.read(tmp, 0, tmp.length))!=-1){
				baos.write(tmp,0,len);
			}
			
			tmp = baos.toByteArray();
			
			ByteBuffer mBuf = ByteBuffer.allocateDirect((int) tmp.length);
			mBuf.put(tmp);
			mBuf.rewind();
			
			glShaderSource(id, mBuf);
			
			in.close();
			
			glCompileShader(id);
			
			if(GL11.GL_TRUE != glGetShader(id, GL_COMPILE_STATUS))
				throw new RuntimeException("COMPILE_STATUS != GL_TRUE");
		} catch (Exception e) {
			throw new RuntimeException("Exception while creating shader "+name+": "+e.getMessage(),e);
		}finally{
			printLog();
		}
	}
	
	public void printLog(){
		System.out.print(glGetShaderInfoLog(id, 1024*1024));
	}
	
	public int getId(){
		return id;
	}
	
	public void delete(){
		glDeleteShader(id);
	}
	
	public void set(){
		
	}
}
